package cn.tedu.mall.product.webapi.config;

import cn.tedu.mall.product.webapi.filter.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;

@Configuration
@EnableWebSecurity(debug = true)
//是否开启全局方法保护，在请求进入方法之前验证权限，true表示是
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    /**
     * configure(AuthenticationManager auth)
     * 和认证管理器有关,但凡是认证流程,都要经过认证管理器,无论那种认证方式
     * 指纹认证,用户名密码认证,手机验证码认证,视网膜,人脸识别认证
     * 区别在于有的认证逻辑,spring security是内置认证管理器的,比如用户名密码比如basic认证
     * 有的需要自定义的 比如指纹
     */
    @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }
    /**
     * configure(HttpSecurity http)
     * 就是操作spring security内置过滤器链中所有过滤器的入口
     * 比如是否使用用户名密码登录过滤器 是否开启csrf过滤器(是否使用spring security的跨域伪造攻击逻辑)
     */
    @Override protected void configure(HttpSecurity http) throws Exception {
        /**
         * 首先,开放一些公共权限,比如swagger页面,html js css等 web资源,无需认证授权
         */
        http.cors().disable();
        http.csrf().disable();
        http.formLogin().disable();
        http.authorizeRequests().antMatchers("/",
            "/*.html",
            "/favicon.ico",
            "/**/*.html",
            "/**/*.css",
            "/**/*.js",
            "/swagger-resources/**",
            "/v2/api-docs/**").permitAll().anyRequest().authenticated();
        http.addFilterAt(jwtAuthenticationFilter, LogoutFilter.class);
        /**
         * 其他不开放的资源,需要认证授权
         */
        /*http.authorizeRequests().anyRequest().authenticated();*/
        /**
         * 怎么认证,在酷鲨项目中,没有使用spring security内置用户名密码认证流程,我们使用的是jwt
         */

    }
    /**
     * configure(WebSecurity web)
     * 用处不多,能决定哪些请求是可以不通过过滤器链的
     */
    @Override public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }
}
